<?php

namespace App\Models\Train\Trains\Repositories;

use App\Models\Train\Trains\Train;
use App\Trip\Repository\BaseRepository;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use JetBrains\PhpStorm\Pure;

class TrainsRepository extends BaseRepository implements Interfaces\TrainsRepositoryInterface
{

    #[Pure] public function __construct(Train $trains)
    {
        parent::__construct($trains);
    }

    /**
     * @throws Exception
     */
    public function addTrain($data): Train
    {
        $train = $this->findByTrainCode($data['train_code']);
        if ($train) {
            return $train;
        }
        return $this->create($data);
    }

    public function findByTrainCode(string $train_code): Train|null
    {

        $cache_key = "Train:info:{$train_code}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }

        $train = $this->findOneBy([
            'train_code' => $train_code,
        ]);

        if (!$train) {
            return null;
        }

        Cache::put($cache_key, $train, config('trip.ttl.day'));

        return $train;

    }

    public function listByStation(array $params): Collection
    {
        // TODO: Implement listByStation() method.
    }
}